<template>
  <div class="goods-detail">
    <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="$router.go(-1)">
      <template #right>
        <div class="cart-icon-wrapper" @click="gotoshoppingcar">
          <van-icon name="shopping-cart-o" size="20" />
          <van-badge v-if="cartStore.totalCount > 0" :content="cartStore.totalCount" class="cart-badge" />
        </div>
      </template>
    </van-nav-bar>

    <div class="swiper-container">
      <van-swipe class="my-swipe" :autoplay="2500" indicator-color="white">
        <van-swipe-item v-for="(item, index) in gallery" :key="index">
          <img :src="item" class="banner-image" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <div class="goods-info">
      <div class="price-section">
        <span class="retail-price">¥{{ goodsInfo.retailPrice }}</span>
        <span class="counter-price" v-if="goodsInfo.counterPrice">¥{{ goodsInfo.counterPrice }}</span>
      </div>
      <h1 class="goods-name">{{ goodsInfo.name }}</h1>
      <div class="brief">{{ goodsInfo.brief }}</div>
    </div>

    <div class="spec-section" v-for="spec in specificationList" :key="spec.name">
      <h3>{{ spec.name }}</h3>
      <div class="spec-options">
        <span v-for="value in spec.valueList" :key="value.id" class="spec-option" :class="{
          'selected': isSpecSelected(spec.name, value.value),
          'disabled': isSpecDisabled(spec.name, value.value)
        }" @click="selectSpec(spec.name, value)">
          {{ value.value }}
        </span>
      </div>
    </div>

    <div class="attribute-section">
      <h3>商品属性</h3>
      <div v-for="attr in attribute" :key="attr.id" class="attribute-item">
        <strong>{{ attr.attribute }}：</strong>
        <span>{{ attr.value }}</span>
      </div>
    </div>

    <div class="detail-section">
      <h3 class="detail-title">商品详情</h3>
      <div v-html="goodsInfo.detail"></div>
    </div>

    <div class="action-bar">
      <button class="add-to-cart" @click="addToCart">加入购物车</button>
      <button class="buy-now" @click="addToCart">立即购买</button>
    </div>

    <van-popup v-model:show="showSpecPopup" position="bottom" round :style="{ height: '60%' }">
      <div class="spec-popup">
        <div class="popup-header">
          <div class="selected-info">
            <img :src="selectedImage" class="popup-image" />
            <div class="popup-price">
              <span>¥{{ goodsInfo.retailPrice }}</span>
              <span v-if="goodsInfo.counterPrice">¥{{ goodsInfo.counterPrice }}</span>
            </div>
          </div>
          <van-icon name="cross" class="close-icon" @click="showSpecPopup = false" />
        </div>

        <div class="popup-specs">
          <div class="spec-group" v-for="spec in specificationList" :key="spec.name">
            <h4>{{ spec.name }}</h4>
            <div class="spec-options">
              <span v-for="value in spec.valueList" :key="value.id" class="spec-option" :class="{
                'selected': isSpecSelected(spec.name, value.value),
                'disabled': isSpecDisabled(spec.name, value.value)
              }" @click="selectSpec(spec.name, value)">
                {{ value.value }}
              </span>
            </div>
          </div>
        </div>

        <div class="quantity-selector">
          <span>购买数量</span>
          <van-stepper v-model="quantity" integer min="1" :max="stock" />
        </div>

        <div class="popup-footer">
          <button class="confirm-btn" @click="confirmAddToCart">确定</button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getGoodsDetail } from '@/api/home'
import { useCartStore } from '@/stores/cart'
import { showSuccessToast, showFailToast } from 'vant'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()

const goodsId = ref(route.query.id)
const goodsInfo = ref({})
const specificationList = ref([])
const attribute = ref([])
const selectedSpecs = ref({})
const gallery = ref([])
const showSpecPopup = ref(false)
const quantity = ref(1)
const stock = ref(0)

const fetchGoodsDetail = async () => {
  try {
    const response = await getGoodsDetail({ id: goodsId.value })
    if (response.errno === 0) {
      goodsInfo.value = response.data.info
      specificationList.value = response.data.specificationList
      attribute.value = response.data.attribute
      gallery.value = response.data.info.gallery
      stock.value = response.data.info.stock || 0

      if (specificationList.value.length > 0) {
        specificationList.value.forEach(spec => {
          if (spec.valueList.length > 0) {
            selectedSpecs.value[spec.name] = spec.valueList[0].value
          }
        })
      }
    }
  } catch (error) {
    console.error('Failed to fetch goods detail:', error)
    showFailToast('Failed to fetch goods detail')
  }
}

const isSpecSelected = (specName, specValue) => {
  return selectedSpecs.value[specName] === specValue
}

const isSpecDisabled = (specName, specValue) => {
  return false
}

const selectSpec = (specName, specValue) => {
  if (isSpecDisabled(specName, specValue.value)) return
  selectedSpecs.value[specName] = specValue.value
}

const addToCart = () => {
  if (specificationList.value.length > 0) {
    showSpecPopup.value = true
    return
  }
  cartStore.addToCart(goodsInfo.value, selectedSpecs.value, quantity.value)
  showSuccessToast({
    message: '已加入购物车',
    className: 'custom-toast'
  })
}

const confirmAddToCart = () => {
  const requiredSpecs = specificationList.value.length
  const selectedSpecsCount = Object.keys(selectedSpecs.value).length

  if (requiredSpecs > 0 && selectedSpecsCount < requiredSpecs) {
    showToast('请选择完整规格')
    return
  }

  cartStore.addToCart(goodsInfo.value, selectedSpecs.value, quantity.value)
  showSpecPopup.value = false
  showSuccessToast({
    message: '已加入购物车',
    className: 'custom-toast'
  })
}

const selectedImage = computed(() => {
  return gallery.value[0] || ''
})

const gotoshoppingcar = () => {
  router.push('/shopping')
}

onMounted(() => {
  fetchGoodsDetail()
})
</script>

<style scoped>
.goods-detail {
  padding-bottom: 100px;
  background-color: #f7f7f7;
  min-height: 100vh;
  min-width: 78vh;
}

.swiper-container {
  width: 100%;
  height: 375px;
  overflow: hidden;
  background-color: #fff;
}

.my-swipe {
  width: 100%;
  height: 100%;
}

.my-swipe .van-swipe-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.banner-image {
  width: 100%;
  height: auto;
  object-fit: fill;
}

.goods-info {
  padding: 15px;
  background: white;
  margin-bottom: 10px;
}

.price-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.retail-price {
  font-size: 24px;
  color: #ff2f55;
  font-weight: bold;
  margin-right: 10px;
}

.counter-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-right: 15px;
}

.sold-count {
  font-size: 12px;
  color: #999;
}

.goods-name {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
  line-height: 1.4;
}

.brief {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.spec-section {
  margin-bottom: 10px;
  padding: 15px;
  background: white;
}

.spec-section h3 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #333;
  font-weight: normal;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-option {
  padding: 5px 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.spec-option.selected {
  border-color: #ff2f55;
  color: #ff2f55;
  background-color: #fff0f0;
}

.spec-option.disabled {
  color: #ccc;
  background-color: #f7f7f7;
  cursor: not-allowed;
  text-decoration: line-through;
}

.attribute-section {
  margin-bottom: 10px;
  padding: 15px;
  background: white;
}

.attribute-section h3 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #333;
  font-weight: normal;
}

.attribute-item {
  font-size: 13px;
  margin-bottom: 8px;
  color: #666;
  display: flex;
}

.attribute-item strong {
  width: 80px;
  color: #999;
}

.detail-section {
  padding: 15px;
  background: white;
}

.detail-title {
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  display: flex;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.add-to-cart {
  flex: 1;
  background: #ff9500;
  color: white;
  border: none;
  font-size: 16px;
}

.buy-now {
  flex: 1;
  background: #ff2f55;
  color: white;
  border: none;
  font-size: 16px;
}

.spec-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.popup-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 15px;
}

.popup-price {
  display: flex;
  flex-direction: column;
}

.popup-price span:first-child {
  color: #ff2f55;
  font-size: 18px;
  font-weight: bold;
}

.popup-price span:last-child {
  color: #999;
  font-size: 12px;
  text-decoration: line-through;
}

.popup-stock {
  position: absolute;
  right: 15px;
  bottom: 15px;
  color: #999;
  font-size: 12px;
}

.close-icon {
  position: absolute;
  right: 10px;
  top: 10px;
  font-size: 18px;
  color: #999;
}

.popup-specs {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.spec-group {
  margin-bottom: 20px;
}

.spec-group h4 {
  font-size: 14px;
  margin-bottom: 10px;
  color: #666;
  font-weight: normal;
}

.quantity-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

.popup-footer {
  padding: 10px 15px;
}

.confirm-btn {
  width: 100%;
  height: 40px;
  background: #ff2f55;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 16px;
}

/* 购物车图标样式 */
.cart-icon-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  margin-left: 16px;
  padding: 8px;
}

.cart-icon-wrapper .van-icon {
  color: #333;
  transition: transform 0.3s ease;
}

.cart-icon-wrapper:active .van-icon {
  transform: scale(1.2);
}

.cart-badge {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(30%, -30%);
}

:deep(.custom-toast) {
  background: rgba(0, 0, 0, 0.8);
  border-radius: 20px;
  padding: 12px 24px;
  font-size: 14px;
}

:deep(.van-toast--success) {
  color: #fff;
}

:deep(.van-toast__icon) {
  color: #fff;
  font-size: 20px;
}
</style>